import { showToast } from 'vant';
// @ts-ignore
import jsonp from "jsonp";
import exp from "constants";

/**
 * url是否为外部链接
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
    return /^(https?:|http?:|mailto:|tel:)/.test(path)
}
export function fen2Yuan(fen:number) {
    return 0.01*fen
}
export function toThousands(num:number|undefined) {
    let n = (num || 0).toString(), result = '';
    while (n.length > 3) {
        result = ',' + n.slice(-3) + result;
        n = n.slice(0, n.length - 3);
    }
    if (n) { result = n + result; }
    return result;
}

export function fen2Yuan2(fen:number) {
    return toThousands(fen2Yuan(fen))
}
export function copyText(text:string,successMsg?:string){
    navigator.clipboard.writeText(text).then(() => {
        if(successMsg){
            showToast({ message: successMsg, icon: 'success', })
        }
    }).catch(error => {
        //如果用户没有授权，会抛出错误
        showToast({ message: "复制失败 :"+ error.message, icon: 'fail', })
    });
}
export function thousandDivisor(num:number){
    if(num<1001)	return ''+num
    else if(num>=1001&&num<=100001) return Math.floor(num/1000)+'k+'
    else return Math.floor(num/10000)+'w+'
}

export function lengthCutting(str:string, num:number) {
    let strArr = [];
    for (let i = 0; i <str.length ; i+=num) {
        strArr.push(str.slice(i,i+num))
    }
    return strArr
}

/**
 * 将颜色转为rgba格式
 */
export function colorRgba(sHex:string, alpha:number) {
// 十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
    /* 16进制颜色转为RGB格式 */
    let sColor = sHex.toLowerCase()
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = '#'
            for (let i = 1; i < 4; i += 1) {
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
            }
            sColor = sColorNew
        }
        // 处理六位的颜色值
        var sColorChange = []
        for (let i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
        }
        // return sColorChange.join(',')
        return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
    }
    else {
        return sColor
    }
}

/**
 * 加载富文本
 */
export function getCkeditValue(url:string, jsonpCallback:any) {

    if('https:' == document.location.protocol){
        url = url.replace(/^http/,"https");
    }

    //加载富文本
    let options = {
        emulateJSON: true,
        param: "jsonpCallback"
    };
    jsonp(url, options, jsonpCallback);
}